package com.kaigejava.juc.cas;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author kaigejava
 * cas ABA问题演示
 */
public class ABADemo1 {
    static AtomicInteger atomicInteger = new AtomicInteger(2020);
    public static void main(String[] args) {

        new Thread(()->{
            System.out.println("A线程内主内存中的值为:"+atomicInteger.get());
            System.out.println("A线程执行一次操作后的值："+
                    atomicInteger.compareAndSet(2020,2021)+" \t"+atomicInteger.get());
            System.out.println("A线程执行第二次操作后的值："
                    +atomicInteger.compareAndSet(2021,2020)+"\t"+atomicInteger.get());
        },"线程A").start();
        //线程2睡上1s.等等下线程A执行一次ABA
        try {TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { }
        new Thread(()->{
            System.out.println("线程2内主内存中的值为:"+atomicInteger.get());
            System.out.println("线程2执行一次操作后的值："
                    +atomicInteger.compareAndSet(2020,2019)+"\t"+atomicInteger.get());
        },"线程2").start();
    }
}
